import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

// vuex插件实现数据持久化存储
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    localStorage.setItem('state', JSON.stringify(state))
  })
}

function getState(params) {
  return JSON.parse(localStorage.getItem('state'))?.[params]
}

export default new Vuex.Store({
  state: {
    token: getState('token') || '',
    userInfo: getState('userInfo') || null,
    darkMode: getState('darkMode') || '', // 暗夜模式
    bookList: [],
    detailItemArr: [],
    commentsArr: getState('commentsArr') || [], // 评论数据
    cacheCommentsArr: getState('cacheCommentsArr') || [], // 缓存未发布的评论数据
  },
  plugins: [myPlugin],
  mutations: {
    // 1. 设置登陆token和用户信息
    set_token_and_userinfo(state, { token, userInfo }) {
      state.token = token
      state.userInfo = userInfo
    },
    // 2.设置列表数据
    set_book_list(state, list) {
      state.bookList = [...state.bookList, ...list]
    },
    // 3. 设置黑夜模式
    set_dark_mode(state, mode) {
      state.darkMode = mode
    },
    // 4. 设置详情数据
    set_detail_item(state, item) {
      state.detailItemArr = item
    },
    // 5. 添加评论
    set_comments_arr(state, item) {
      state.commentsArr.unshift(item)
    },
    // 6. 缓存住未发布的评论数据
    set_cache_commentsArr(state, item) {
      state.cacheCommentsArr = [item]
    },
  },
  actions: {
    // 1. 登陆接口
    async fetchLogin({ commit }, data) {
      const res = await axios.post('/api/login', data)
      commit('set_token_and_userinfo', {
        token: res.data.data.token,
        userInfo: res.data.data.userInfo,
      })
      return { code: 0, msg: 'success' }
    },
    // 2. 列表接口
    async fetchBookList({ commit }, params) {
      const res = await axios.get('/api/bookList', { params })
      console.log('书籍列表:', res.data.data)
      commit('set_book_list', res.data.data)
      return { code: 0, msg: 'success' }
    },
    // 3. 详情接口
    async fetchDetailItem({ commit }, params) {
      const res = await axios.get('/api/detail', { params })
      console.log('详情:', res.data.data)
      commit('set_detail_item', res.data.data)
      return { code: 0, msg: 'success' }
    },
  },
})
